package com.michael.study.network;

import android.util.Log;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Description:
 *
 * <p>Created by liuguoquan on 2020/6/13 18:08.
 */
public abstract class NetWorkModule implements IEnvironment {

    private static INetWorkInfo mINetWorkInfo;
    private static Map<String, Retrofit> retrofitHashMap = new HashMap<>();
    private OkHttpClient mOkHttpClient;
    private String mBaseUrl;
    private static int mEnvironment = DEV;

    public NetWorkModule() {
        if (mEnvironment == FACTORY) {
            mBaseUrl = getFactoryUrl();
        } else if (mEnvironment == TEST) {
            mBaseUrl = getTestUrl();
        } else {
            mBaseUrl = getDevUrl();
        }
    }

    public static void init(INetWorkInfo info) {
        mINetWorkInfo = info;
        mEnvironment = DEV;
    }

    protected Retrofit getRetrofit(Class<?> service) {
        if (retrofitHashMap.get(mBaseUrl) != null) {
            return retrofitHashMap.get(mBaseUrl);
        }

        Retrofit.Builder builder = new Retrofit.Builder();
        builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        builder.addConverterFactory(GsonConverterFactory.create());
        builder.baseUrl(mBaseUrl);
        builder.client(getOkHttpClient());
        Retrofit retrofit = builder.build();
        retrofitHashMap.put(mBaseUrl + service.getName(), retrofit);
        return retrofit;
    }

    private OkHttpClient getOkHttpClient() {
        if (mOkHttpClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.eventListener(new HttpEventListener());
            if (getInterceptor() != null) {
                builder.addInterceptor(getInterceptor());
            }
            builder.addInterceptor(new CommonRequestInterceptor(mINetWorkInfo));
            builder.addInterceptor(new CommonResponseInterceptor());
            if (mINetWorkInfo != null && (mINetWorkInfo.isDebug())) {
                HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
                httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(httpLoggingInterceptor);
            }
            mOkHttpClient = builder.build();
        }
        return mOkHttpClient;
    }

    protected abstract Interceptor getInterceptor();
}
